package com.example.demo.lock;

import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collections;

@Component("lettuceLock")
public class LettuceLock implements RedisLock {

    @Autowired
    private RedisClient redisClient;

    @Override
    public boolean lock(String lockValue, int seconds) {
        try (StatefulRedisConnection<String, String> connect = redisClient.connect()){
            SetArgs setArgs = SetArgs.Builder.nx().ex(seconds);
            // 同步请求；lettuce基于netty的可以实现异步返回结果
            final String result = connect.sync().set(lockValue, lockValue, setArgs);
            connect.close();
            return "OK".equals(result);
        }
        /*final
        try(Jedis jedis = jedisPool.getResource()) {
            return "OK".equals(jedis.set(lockValue, lockValue, "NX", "EX", seconds));
        }*/
    }

    @Override
    public boolean tryLock(String lockValue, int seconds) {
        return false;
    }

    @Override
    public boolean release(String lock) {
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        try(StatefulRedisConnection<String, String> connect = redisClient.connect()) {
            final Object eval = connect.sync().eval(luaScript, ScriptOutputType.INTEGER, new String[]{lock}, new String[]{lock});
//            return jedis.eval(luaScript, Collections.singletonList(lock), Collections.singletonList(lock)).equals(1L);
            connect.close();
            return eval.equals(1L);
        }
    }
}
